import {
  getFileList,
  getFile
} from '@/api/login';
// import { Message } from 'element-ui';

// todo 请求文件列表
/*
  data: {
    type: string;
    appId: string;
  }
*/
const searchFilesList = async(data, pageSize = 1) => {
  const requestData = {
    pageIndex: 0,
    pageSize: pageSize,
    type: [data.type],
    sort: '"uploadTime" DESC',
    condition: data.appId
  };
  return await getFileList(requestData);
};

const conversionBase64 = (blob) => {
  const reader = new FileReader();
  reader.readAsDataURL(blob);
  return new Promise(resolve => {
    reader.onload = ({ target: { result }}) => {
      resolve(result);
    };
  });
};

const saveFileToLocal = (blob, fileName) => {
  const a = document.createElement('a');
  const url = window.URL.createObjectURL(blob);
  const filename = fileName;
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
  a.remove();
};

// todo 下载文件
/*
  data: {
    id: string
    fileName: string
    originName: string
  }

  type: string // pic | file ;   //type === pic 返回base64 否则直接下载打开
*/
const downFile = async(data, type) => {
  const blob = await getFile({
    id: data.id,
    fileName: data.saveName
  });

  if (type === 'pic') {
    return await conversionBase64(blob);
  } else {
    saveFileToLocal(blob, data.originName);
  }
};

export {
  searchFilesList,
  downFile
};
